package com.my.admin.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.admin.entity.Article;
import com.my.admin.entity.ArticleTag;
import com.my.admin.service.ArticleService;
import com.my.admin.service.ArticleTagService;
import com.my.admin.service.ShiroService;
import com.my.admin.util.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

@RestController
@CrossOrigin
public class ArticleController {

    @Autowired
    private ArticleService service;
    @Autowired
    private ArticleTagService atService;
    @Autowired
    private ShiroService sService;

    @PostMapping("article/get")
    public Rest get(@RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "10") int pageSize, @RequestBody Article article) {
        return Rest.ok().setData("page", service.getList(new Page<>(pageNo, pageSize), article));
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("articles")
    public Rest add(@RequestBody Article article, @RequestHeader("authentication-token") String token) {
        article.setCreateUserId(Convert.toLong(sService.getTokenInfo(token).get("userId")));
        if(service.save(article)) {
            atService.batchInsert(article.getId(), article.getTags());
            return Rest.ok("文章添加成功！");
        }
        return Rest.err("添加失败！");
    }

    @PutMapping("articles")
    public Rest edit(@RequestBody Article article) {
        atService.remove(new QueryWrapper<ArticleTag>().eq("article_id", article.getId()));
        if(service.updateById(article)) {
            atService.batchInsert(article.getId(), article.getTags());
            return Rest.ok("文章修改成功！");
        }
        return Rest.err("修改失败！");
    }

    @DeleteMapping("articles")
    public Rest del(@RequestParam long id) {
        if(service.removeById(id)) {
            atService.remove(new QueryWrapper<ArticleTag>().eq("article_id", id));
            return Rest.ok("删除成功！");
        }
        return Rest.err("删除失败！");
    }

    @GetMapping("article/tags")
    public Rest tags(@RequestParam Long id) {
        return Rest.ok().setData("list", atService.list(new QueryWrapper<ArticleTag>().eq("article_id", id)).stream().map(ArticleTag::getTagId).collect(Collectors.toList()));
    }

}
